import { defineStore } from 'pinia'
import { ref } from 'vue'

/**
 * !!!这个只保存谷歌书签, 不保存用户自定义书签
 */
export const useBookmarkStore = defineStore('bookmark', () => {
    // state
    const flatBookmarkList = ref<any>([]) // 扁平化书签
    const treeBookmarkList = ref<any>([]) // 树形书签

    // action：同步 Chrome 书签
    async function syncChromeBookmark() {
        const bookmarkTree = await window.$GLOBAL.__GLOBAL_CHROME_SERVICE__.getBookmarkTree()

        // 更新树形结构
        treeBookmarkList.value = bookmarkTree

        // 转换为扁平结构
        const getChildren = (bookmarks: any): any[] => {
            if (!bookmarks) return []
            const arr = []
            for (const book of bookmarks) {
                if (book.children) {
                    arr.push(...getChildren(book.children))
                    delete book.children // 删除原始 children 字段
                    arr.push(book)
                } else {
                    arr.push(book)
                }
            }
            return arr
        }

        const flatternBookmark = getChildren(JSON.parse(JSON.stringify(bookmarkTree)))
        flatBookmarkList.value = flatternBookmark
    }

    return {
        flatBookmarkList,
        treeBookmarkList,
        syncChromeBookmark
    }
})
